<?php

namespace App\Console\Commands;

use App\Enums\MessagePublishStatus;
use App\Models\MessageReceiver;
use App\Models\MessageTemplate;
use App\Models\Notice;
use Illuminate\Console\Command;

class MessageSendCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'message:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '根据消息模板发送站内信';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //查看所有待发布的站内信模板
        $templates = MessageTemplate::query()
            ->where('publish_status', MessagePublishStatus::INIT)
            ->where('publish_time', '<=', now())
            ->limit(10) //每次最多处理10条消息模板
            ->get();

        /** @var MessageTemplate $template */
        foreach ($templates as $template) {
            \DB::transaction(function () use ($template) {
                $template->publish_status = MessagePublishStatus::PUBLISHING;
                $template->save();
                $receivers = $template->receivers;
                while (true) {
                    $batch = $receivers->splice(0, 1);
                    if (0 === count($batch)) {
                        break;
                    }
                    $batchValues = [];
                    /** @var MessageReceiver $receiver */
                    foreach ($batch as $receiver) {
                        $content = $template->content;
                        $content = str_replace('{keyword1}', $receiver->keyword1 ?: '', $content);
                        $content = str_replace('{keyword2}', $receiver->keyword2 ?: '', $content);
                        $content = str_replace('{keyword3}', $receiver->keyword3 ?: '', $content);
                        $batchValues = [
                            'agent_id' => $template->agent_id,
                            'title' => $template->title,
                            'content' => $content,
                            'template_id' => $template->id,
                            'to_user_id' => $receiver->receiver_id,
                            'publish_time' => now(),
                            'created_at' => now(),
                            'updated_at' => now(),
                        ];
                    }
                    Notice::query()->insert($batchValues);
                }
                $template->publish_status = MessagePublishStatus::PUBLISHED;
                $template->save();
                $this->output->writeln(sprintf('模板ID:%s, 发送完成', $template->id));
            });
        }

        return 0;
    }
}
